<template>
  <div class="video-player-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      :title="videoTitle" 
      left-arrow 
      @click-left="onClickLeft" 
      fixed 
      placeholder
      :z-index="1001"
    >
      <template #right>
        <van-icon name="more-o" @click="showMoreActions" />
      </template>
    </van-nav-bar>

    <!-- 视频播放器区域 -->
    <div class="video-container">
      <!-- 视频播放器 -->
      <div v-if="currentVideo && currentVideo.url" class="video-wrapper" ref="videoWrapper">
        <video
          v-if="currentVideo && currentVideo.url"
          ref="videoPlayer"
          class="video-element"
          :poster="currentVideo.poster"
          :preload="videoPreloadMode"
          playsinline
          webkit-playsinline
          x5-video-player-type="h5"
          x5-video-player-fullscreen="true"
          x5-video-orientation="portraint"
          crossorigin="anonymous"
          :controls="videoSettings.useNativeControls"
          :loop="videoSettings.loop"
          :muted="videoSettings.muted"
          :autoplay="videoSettings.autoplay"
          :playbackRate="videoSettings.playbackRate"
          @loadstart="onVideoLoadStart"
          @loadedmetadata="onVideoLoadedMetadata"
          @progress="onVideoProgress"
          @canplay="onVideoCanPlay"
          @canplaythrough="onVideoCanPlayThrough"
          @play="onVideoPlay"
          @pause="onVideoPause"
          @ended="onVideoEnded"
          @timeupdate="onVideoTimeUpdate"
          @error="onVideoError"
          @waiting="onVideoWaiting"
          @stalled="onVideoStalled"
        >
          <!-- 提供多种格式的视频源，增强兼容性 -->
          <source v-if="currentVideo && currentVideo.url" :src="currentVideo.url" type="video/mp4">
          <!-- 如果有WebM格式，可以添加 -->
          <!-- <source v-if="currentVideo && currentVideo.webm_url" :src="currentVideo.webm_url" type="video/webm"> -->
          <!-- 提供后备内容，当浏览器不支持video元素时显示 -->
          <p>您的浏览器不支持HTML5视频播放，请升级浏览器或使用其他浏览器。</p>
        </video>

        <!-- 空状态显示 -->
        <div v-if="!currentVideo && !isLoading" class="empty-state">
          <div class="empty-content">
            <div class="empty-icon">📹</div>
            <div class="empty-text">暂无视频内容</div>
            <div class="empty-desc">请检查课程是否包含视频资源</div>
          </div>
        </div>
        
        <!-- 自定义控制层 -->
        <div class="video-controls" v-show="showControls" @click="toggleControls">
          <div class="controls-overlay">
            <!-- 播放/暂停按钮 -->
            <div class="play-button" @click.stop="togglePlay">
              <van-icon 
                :name="isPlaying ? 'pause' : 'play'" 
                size="48" 
                color="#fff"
              />
            </div>
            
            <!-- 进度条 -->
            <div class="progress-container" @click.stop>
              <div class="time-info">
                <span class="current-time">{{ formatTime(currentTime) }}</span>
                <span class="duration">{{ formatTime(duration) }}</span>
              </div>
              <van-slider
                v-model="progressValue"
                :max="100"
                @change="onProgressChange"
                @drag-start="onProgressDragStart"
                @drag-end="onProgressDragEnd"
                active-color="#1989fa"
                inactive-color="rgba(255,255,255,0.3)"
              />
            </div>
            
            <!-- 控制按钮组 -->
            <div class="control-buttons">
              <!-- 静音按钮 -->
              <div class="control-button" @click.stop="toggleMuted">
                <van-icon 
                  :name="videoSettings.muted ? 'volume-o' : 'volume'" 
                  size="20" 
                  color="#fff"
                />
              </div>
              
              <!-- 循环播放按钮 -->
              <div class="control-button" @click.stop="toggleLoop">
                <van-icon 
                  :name="videoSettings.loop ? 'replay' : 'play-circle-o'" 
                  size="20" 
                  color="#fff"
                  :style="{ opacity: videoSettings.loop ? 1 : 0.7 }"
                />
              </div>
              
              <!-- 播放速度按钮 -->
              <div class="control-button" @click.stop="showSpeedSelector">
                <span class="speed-text">{{ videoSettings.playbackRate }}x</span>
              </div>
              
              <!-- 全屏按钮 -->
              <div class="control-button" @click.stop="toggleFullscreen">
                <van-icon 
                  :name="isFullscreen ? 'shrink' : 'enlarge'" 
                  size="20" 
                  color="#fff"
                />
              </div>
            </div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <transition name="fade">
          <div class="loading-overlay" v-if="isLoading && !isVideoReady">
            <div class="loading-content">
              <van-loading size="24" color="#fff" />
              <div class="loading-info">
                <div class="loading-text">{{ loadingText }}</div>
                <div v-if="showLoadingProgress" class="loading-progress">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: loadingProgress + '%' }"></div>
                  </div>
                  <div class="progress-text">{{ loadingProgress }}%</div>
                </div>
                <div class="loading-tips">
                  <div class="tip-item">• 视频正在缓冲，请稍候</div>
                  <div class="tip-item" v-if="isSlowNetwork">• 检测到网络较慢 ({{ networkStatus }})，正在优化加载</div>
                  <div class="tip-item" v-else-if="networkStatus !== 'unknown'">• 网络状态：{{ networkStatus.toUpperCase() }}</div>
                  <div class="tip-item" v-if="stallCount > 0">• 已优化 {{ stallCount }} 次缓冲卡顿</div>
                  <div class="tip-item" v-if="retryCount > 0">• 第 {{ retryCount }} 次重试加载</div>
                  <div class="tip-item" v-if="bufferHealth < 30 && bufferHealth > 0">• 缓冲健康度：{{ Math.round(bufferHealth) }}%</div>
                </div>
                <div v-if="showRetryButton" class="retry-section">
                  <van-button
                    type="primary"
                    size="small"
                    @click="retryVideoLoad"
                    :loading="isLoading"
                  >
                    重新加载 ({{ retryCount }}/{{ maxRetries }})
                  </van-button>
                </div>
              </div>
            </div>
          </div>
        </transition>
        <!-- 视频信息 -->
        <div class="video-info">
          <h2 class="video-title">{{ currentVideo.title }}</h2>
          <p class="video-description">{{ currentVideo.description }}</p>
          <div class="video-meta">
            <div class="meta-item">
              <van-icon name="clock-o" />
              <span>{{ formatTime(currentVideo.duration || 0) }}</span>
            </div>
            <div class="meta-item">
              <van-icon name="eye-o" />
              <span>{{ currentVideo.viewCount || 0 }}次播放</span>
            </div>
            <div class="meta-item">
              <van-icon name="calendar-o" />
              <span>{{ formatDate(currentVideo.createdAt) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <van-empty
        v-else
        image="search"
        description="视频不存在或暂未上传"
        class="empty-state"
      >
        <van-button
          round
          type="primary"
          class="bottom-button"
          @click="router.go(-1)"
        >
          返回上一页
        </van-button>
      </van-empty>
    </div>

    <!-- 播放列表 -->
    <div v-if="!isLoading" class="playlist-section">
      <div class="playlist-header">
        <h3>课程列表</h3>
        <span class="playlist-count">共{{ playlist.length }}个视频</span>
      </div>
      <div v-if="playlist.length > 0" class="playlist-content">
        <div
          v-for="(video, index) in playlist"
          :key="video.id"
          class="playlist-item"
          :class="{
            active: video.id === currentVideo?.id,
            loading: isLoading && video.id === currentVideo?.id,
            completed: completedLessons.has(video.id),
            locked: sequentialPlayback && !canPlayLesson(index)
          }"
          @click="playVideo(video, index)"
        >
          <div class="item-index">
            <span v-if="completedLessons.has(video.id)" class="completed-icon">✓</span>
            <span v-else-if="sequentialPlayback && !canPlayLesson(index)" class="locked-icon">🔒</span>
            <span v-else>{{ index + 1 }}</span>
          </div>
          <div class="item-thumbnail">
            <van-image
              :src="video.poster"
              fit="cover"
              :alt="video.title"
              class="thumbnail-image"
              :class="{ 'locked-thumbnail': sequentialPlayback && !canPlayLesson(index) }"
            />
            <div class="play-icon" v-if="video.id === currentVideo?.id && isPlaying">
              <van-icon name="volume-o" size="16" color="#1989fa" />
            </div>
            <div v-if="sequentialPlayback && !canPlayLesson(index)" class="lock-overlay">
              <van-icon name="lock" size="20" color="#999" />
            </div>
          </div>
          <div class="item-content">
            <h4 class="item-title" :class="{ 'locked-title': sequentialPlayback && !canPlayLesson(index) }">
              {{ video.title }}
            </h4>
            <div class="item-meta">
              <span class="item-duration">{{ formatTime(video.duration) }}</span>
              <van-tag v-if="completedLessons.has(video.id)" type="success">已完成</van-tag>
              <van-tag v-else-if="sequentialPlayback && !canPlayLesson(index)" type="warning">需解锁</van-tag>
            </div>
          </div>
        </div>
      </div>
      <van-empty
        v-else
        image="search"
        description="暂无课程列表"
        class="empty-state"
      />
    </div>

    <!-- 更多操作弹窗 -->
    <van-action-sheet
      v-model:show="showActionSheet"
      :actions="moreActions"
      @select="onActionSelect"
      cancel-text="取消"
    />

    <!-- 报名检查弹窗 -->
    <EnrollmentCheck
      :show="showEnrollmentModal"
      :course-info="courseInfo"
      @close="handleEnrollmentClose"
      @enrolled="handleEnrollmentSuccess"
    />

    <!-- 顺序播放提示弹窗 -->
    <van-dialog
      v-model:show="showSequentialModal"
      title="需要按顺序学习"
      message="请先完成前面的课时，然后才能学习后续内容"
      :show-cancel-button="false"
      confirm-button-text="知道了"
      confirm-button-color="#1989fa"
    />
  </div>
</template>

<script setup name="VideoPlayerPage" lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { StudyService } from '@/api/services';
import { PerformanceMonitor } from '@/utils/performance';
import { videoOptimizer } from '@/utils/videoOptimizer';
import { VideoProgressTracker } from '@/utils/videoProgressTracker';
import EnrollmentCheck from '@/components/EnrollmentCheck.vue';

const router = useRouter();
const route = useRoute();

// 注册组件
const components = {
  EnrollmentCheck
};

// 响应式数据
const videoPlayer = ref<HTMLVideoElement | null>(null);
const videoWrapper = ref<HTMLElement | null>(null);
const currentVideo = ref<any>(null);
const playlist = ref<any[]>([]);
const currentIndex = ref(0);

// 缓存数据，避免重复API调用
const courseCache = ref<Map<number, any>>(new Map());

// 进度跟踪器
const progressTracker = ref<VideoProgressTracker | null>(null);
const progressTrackerInitialized = ref(false); // 防止重复初始化

// 报名检查相关
const showEnrollmentModal = ref(false);
const isEnrolled = ref(false);
const enrollmentChecking = ref(false);
const courseInfo = ref<any>(null);

// 顺序播放控制
const sequentialPlayback = ref(true); // 是否启用顺序播放
const completedLessons = ref<Set<number>>(new Set()); // 已完成的课时ID集合
const showSequentialModal = ref(false); // 显示顺序播放提示弹窗

// 播放状态
const isPlaying = ref(false);
const isLoading = ref(false);
const isInitializing = ref(false); // 添加初始化状态
const showControls = ref(true);
const isFullscreen = ref(false);
const isDragging = ref(false);
const isVideoReady = ref(false); // 添加视频就绪状态
let loadingTimeout: NodeJS.Timeout | null = null;

// 视频加载进度
const loadingProgress = ref(0);
const loadingText = ref('正在加载视频...');
const showLoadingProgress = ref(false);

// 重试机制
const retryCount = ref(0);
const maxRetries = ref(3);
const showRetryButton = ref(false);

// 网络状态
const networkStatus = ref('unknown');
const isSlowNetwork = ref(false);

// 视频预加载缓存
const videoPreloadCache = new Map();
const preloadQueue = ref<any[]>([]);
const isPreloading = ref(false);

// 视频预加载模式 - 根据网络状况动态调整
const videoPreloadMode = ref<'none' | 'metadata' | 'auto'>('metadata');

// 视频缓冲状态
const isBuffering = ref(false);
const bufferHealth = ref(0); // 缓冲健康度 (0-100)
const stallCount = ref(0); // 卡顿次数

// 视频设置选项
const videoSettings = ref({
  muted: false,      // 是否静音
  loop: false,       // 是否循环播放
  autoplay: false,   // 是否自动播放（注意：大多数浏览器需要muted为true才允许自动播放）
  playbackRate: 1.0, // 播放速度
  useNativeControls: false // 是否使用浏览器原生控件
});

// 时间相关
const currentTime = ref(0);
const duration = ref(0);
const progressValue = ref(0);

// UI状态
const showActionSheet = ref(false);
const videoTitle = ref('视频播放');

// 控制器隐藏定时器
let controlsTimer: NodeJS.Timeout | null = null;



// 更多操作选项
const moreActions = [
  { name: '分享视频', value: 'share' },
  { name: '下载视频', value: 'download' },
  { name: `${videoSettings.value.loop ? '关闭' : '开启'}循环播放`, value: 'loop' },
  { name: `${videoSettings.value.muted ? '取消静音' : '静音'}`, value: 'muted' },
  { name: '播放速度', value: 'speed' },
  { name: `${videoSettings.value.useNativeControls ? '使用自定义控件' : '使用浏览器控件'}`, value: 'controls' },
  { name: '画质选择', value: 'quality' },
];

// 页面方法
const onClickLeft = () => {
  router.go(-1);
};

const showMoreActions = () => {
  showActionSheet.value = true;
};

const onActionSelect = (action: any) => {
  switch (action.value) {
    case 'loop':
      videoSettings.value.loop = !videoSettings.value.loop;
      showToast(`${videoSettings.value.loop ? '已开启' : '已关闭'}循环播放`);
      break;
    case 'muted':
      videoSettings.value.muted = !videoSettings.value.muted;
      showToast(`${videoSettings.value.muted ? '已静音' : '已取消静音'}`);
      break;
    case 'controls':
      videoSettings.value.useNativeControls = !videoSettings.value.useNativeControls;
      showToast(`已切换为${videoSettings.value.useNativeControls ? '浏览器原生控件' : '自定义控件'}`);
      break;
    case 'speed':
      showSpeedSelector();
      break;
    default:
      showToast(`${action.name}功能开发中...`);
  }
  showActionSheet.value = false;
  
  // 更新操作选项文本
  updateMoreActions();
};

// 更新更多操作选项文本
const updateMoreActions = () => {
  moreActions[2].name = `${videoSettings.value.loop ? '关闭' : '开启'}循环播放`;
  moreActions[3].name = `${videoSettings.value.muted ? '取消静音' : '静音'}`;
  moreActions[5].name = `${videoSettings.value.useNativeControls ? '使用自定义控件' : '使用浏览器控件'}`;
  
  // 保存设置到本地存储
  saveVideoSettings();
};

// 保存视频设置到本地存储
const saveVideoSettings = () => {
  try {
    localStorage.setItem('videoSettings', JSON.stringify({
      muted: videoSettings.value.muted,
      loop: videoSettings.value.loop,
      autoplay: videoSettings.value.autoplay,
      playbackRate: videoSettings.value.playbackRate,
      useNativeControls: videoSettings.value.useNativeControls
    }));
    console.log('视频设置已保存');
  } catch (e) {
    console.error('保存视频设置失败:', e);
  }
};

// 播放速度选择
const showSpeedSelector = () => {
  // 这里可以实现一个播放速度选择器
  // 简单起见，这里只是循环切换几个常用速度
  const speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
  const currentIndex = speeds.indexOf(videoSettings.value.playbackRate);
  const nextIndex = (currentIndex + 1) % speeds.length;
  videoSettings.value.playbackRate = speeds[nextIndex];
  
  if (videoPlayer.value) {
    videoPlayer.value.playbackRate = videoSettings.value.playbackRate;
  }
  
  showToast(`播放速度: ${videoSettings.value.playbackRate}x`);
};

// 视频播放控制
const togglePlay = () => {
  if (!videoPlayer.value) return;

  if (isPlaying.value) {
    console.log('暂停视频');
    videoPlayer.value.pause();
  } else {
    console.log('播放视频');
    // 如果设置了自动播放但被浏览器阻止，可能需要先静音
    if (!videoSettings.value.muted && !isVideoReady.value) {
      console.log('自动播放可能需要静音，尝试静音播放');
      videoSettings.value.muted = true;
    }
    
    videoPlayer.value.play().catch(error => {
      console.error('播放失败:', error);
      showToast('播放失败，请稍后重试');
    });
  }
};

// 切换静音状态
const toggleMuted = () => {
  videoSettings.value.muted = !videoSettings.value.muted;
  if (videoPlayer.value) {
    videoPlayer.value.muted = videoSettings.value.muted;
  }
  showToast(`${videoSettings.value.muted ? '已静音' : '已取消静音'}`);
  updateMoreActions();
};

// 切换循环播放状态
const toggleLoop = () => {
  videoSettings.value.loop = !videoSettings.value.loop;
  if (videoPlayer.value) {
    videoPlayer.value.loop = videoSettings.value.loop;
  }
  showToast(`${videoSettings.value.loop ? '已开启' : '已关闭'}循环播放`);
  updateMoreActions();
};

const playVideo = (video: any, index: number) => {
  console.log('切换视频:', video.title, video.url);

  // 防止重复加载同一个视频
  if (currentVideo.value && currentVideo.value.id === video.id) {
    console.log('视频已经选中，跳过重复加载');
    return;
  }

  // 检查顺序播放限制
  if (!canPlayLesson(index)) {
    console.log('⚠️ 顺序播放限制：需要先完成前面的课时');
    handleSequentialPlaybackRestriction(index);
    return;
  }

  // 停止当前的进度跟踪
  if (progressTracker.value) {
    progressTracker.value.stopTracking();
    progressTracker.value.destroy();
    progressTracker.value = null;
  }
  // 重置初始化状态，允许为新视频创建跟踪器
  progressTrackerInitialized.value = false;

  // 开始性能监控
  PerformanceMonitor.startTimer(`video-switch-${video.id}`);

  // 立即更新UI状态，提升用户体验
  currentVideo.value = video;
  currentIndex.value = index;
  videoTitle.value = video.title;

  // 重置播放状态
  isVideoReady.value = false;
  isPlaying.value = false;
  isLoading.value = true;
  isBuffering.value = false;
  showLoadingProgress.value = true;
  showRetryButton.value = false;
  retryCount.value = 0;
  stallCount.value = 0;
  bufferHealth.value = 0;

  // 重置播放进度
  currentTime.value = 0;
  duration.value = 0;
  progressValue.value = 0;

  console.log('✅ 视频状态重置完成');

  // 使用 nextTick 确保 DOM 更新后再重新加载视频
  nextTick(() => {
    if (videoPlayer.value) {
      console.log('🔄 开始重新加载视频:', video.url);
      console.log('🔍 当前视频播放器状态:', {
        src: videoPlayer.value.src,
        currentSrc: videoPlayer.value.currentSrc,
        readyState: videoPlayer.value.readyState,
        networkState: videoPlayer.value.networkState
      });

      // 停止当前播放
      videoPlayer.value.pause();

      // 重新加载视频源
      videoPlayer.value.load();

      console.log('✅ 视频重新加载完成，等待加载事件');
      console.log('🔍 重新加载后状态:', {
        src: videoPlayer.value.src,
        currentSrc: videoPlayer.value.currentSrc,
        readyState: videoPlayer.value.readyState,
        networkState: videoPlayer.value.networkState
      });
    } else {
      console.error('❌ 视频播放器元素未找到');
    }
  });
};

const toggleControls = () => {
  showControls.value = !showControls.value;
  resetControlsTimer();
};

const resetControlsTimer = () => {
  if (controlsTimer) {
    clearTimeout(controlsTimer);
  }
  
  if (showControls.value && isPlaying.value) {
    controlsTimer = setTimeout(() => {
      showControls.value = false;
    }, 3000);
  }
};

const toggleFullscreen = () => {
  if (!videoWrapper.value) return;
  
  if (!isFullscreen.value) {
    if (videoWrapper.value.requestFullscreen) {
      videoWrapper.value.requestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  }
};

// 进度控制
const onProgressChange = (value: number) => {
  if (!videoPlayer.value || !duration.value) return;
  
  const newTime = (value / 100) * duration.value;
  videoPlayer.value.currentTime = newTime;
  currentTime.value = newTime;
};

const onProgressDragStart = () => {
  isDragging.value = true;
};

const onProgressDragEnd = () => {
  isDragging.value = false;
};

// 网络状态检测和优化
const detectNetworkSpeed = async () => {
  // 使用优化器检测网络
  videoOptimizer.detectNetwork();
  const networkInfo = videoOptimizer.getNetworkInfo();
  const config = videoOptimizer.getConfig();

  // 更新本地状态
  networkStatus.value = networkInfo.effectiveType;
  isSlowNetwork.value = networkInfo.isSlowNetwork;
  videoPreloadMode.value = config.preloadMode;
  maxRetries.value = config.maxRetries;

  console.log('网络检测完成:', {
    network: networkInfo.effectiveType,
    isSlowNetwork: networkInfo.isSlowNetwork,
    preloadMode: config.preloadMode,
    maxRetries: config.maxRetries
  });

  // 如果没有网络API，通过测试下载速度来判断
  if (networkStatus.value === 'unknown' && currentVideo.value?.url) {
    try {
      const responseTime = await videoOptimizer.testNetworkSpeed(currentVideo.value.url);
      const updatedInfo = videoOptimizer.getNetworkInfo();
      const updatedConfig = videoOptimizer.getConfig();

      // 更新状态
      networkStatus.value = updatedInfo.effectiveType;
      isSlowNetwork.value = updatedInfo.isSlowNetwork;
      videoPreloadMode.value = updatedConfig.preloadMode;
      maxRetries.value = updatedConfig.maxRetries;

      console.log('网络速度测试完成:', {
        responseTime: responseTime + 'ms',
        network: updatedInfo.effectiveType,
        isSlowNetwork: updatedInfo.isSlowNetwork
      });
    } catch (error) {
      console.warn('网络速度测试失败:', error);
    }
  }
};

// 重试视频加载
const retryVideoLoad = () => {
  if (retryCount.value >= maxRetries.value) {
    showToast('已达到最大重试次数，请检查网络连接');
    return;
  }

  retryCount.value++;
  showRetryButton.value = false;
  isLoading.value = true;
  isBuffering.value = false;
  stallCount.value = 0; // 重置卡顿计数

  console.log(`重试加载视频，第${retryCount.value}次`);

  // 重试时调整策略
  if (retryCount.value > 1) {
    // 第二次重试时降低预加载级别
    videoPreloadMode.value = 'none';
    loadingText.value = '重试中，已优化加载策略...';
  } else {
    loadingText.value = `第${retryCount.value}次重试，请稍候...`;
  }

  // 重新设置视频源触发重新加载
  if (videoPlayer.value && currentVideo.value) {
    // 使用优化器获取优化后的URL
    const optimizedUrl = videoOptimizer.getOptimizedVideoUrl(currentVideo.value.url, retryCount.value);

    videoPlayer.value.src = '';

    // 使用优化器计算重试延迟
    const retryDelay = videoOptimizer.getRetryDelay(retryCount.value);
    console.log(`重试延迟: ${retryDelay}ms`);

    setTimeout(() => {
      if (videoPlayer.value) {
        videoPlayer.value.src = optimizedUrl;
        videoPlayer.value.load();
        console.log('重试URL:', optimizedUrl);
      }
    }, retryDelay);
  }
};

// 设置加载超时
const setLoadingTimeout = () => {
  // 清除之前的超时
  if (loadingTimeout) {
    clearTimeout(loadingTimeout);
  }

  // 使用优化器计算超时时间
  const timeoutDuration = videoOptimizer.getTimeoutDuration(retryCount.value);

  console.log(`设置加载超时: ${timeoutDuration / 1000}秒 (网络: ${networkStatus.value}, 重试: ${retryCount.value})`);

  loadingTimeout = setTimeout(() => {
    if (isLoading.value) {
      console.warn('视频加载超时，显示重试选项');
      showRetryButton.value = true;
      loadingText.value = `加载超时 (${Math.round(timeoutDuration / 1000)}s)，请重试`;

      if (retryCount.value < maxRetries.value) {
        // 还有重试机会，不立即隐藏加载界面
        console.log('显示重试按钮');
      } else {
        // 已达到最大重试次数
        isLoading.value = false;
        isVideoReady.value = false;
        showLoadingProgress.value = false;
        showToast('视频加载失败，请检查网络连接或稍后重试');
      }
    }
  }, timeoutDuration);
};

// 清除加载超时
const clearLoadingTimeout = () => {
  if (loadingTimeout) {
    clearTimeout(loadingTimeout);
    loadingTimeout = null;
  }
};

// 预加载视频元数据
const preloadVideoMetadata = (videoUrl: string) => {
  return new Promise((resolve, reject) => {
    // 检查缓存
    if (videoPreloadCache.has(videoUrl)) {
      resolve(videoPreloadCache.get(videoUrl));
      return;
    }

    const video = document.createElement('video');
    video.preload = 'metadata';
    video.crossOrigin = 'anonymous';

    const onLoadedMetadata = () => {
      const metadata = {
        duration: video.duration,
        videoWidth: video.videoWidth,
        videoHeight: video.videoHeight,
        url: videoUrl
      };

      // 缓存元数据
      videoPreloadCache.set(videoUrl, metadata);
      console.log('预加载视频元数据完成:', videoUrl, metadata);

      cleanup();
      resolve(metadata);
    };

    const onError = () => {
      console.warn('预加载视频元数据失败:', videoUrl);
      cleanup();
      reject(new Error('预加载失败'));
    };

    const cleanup = () => {
      video.removeEventListener('loadedmetadata', onLoadedMetadata);
      video.removeEventListener('error', onError);
      video.src = '';
    };

    video.addEventListener('loadedmetadata', onLoadedMetadata);
    video.addEventListener('error', onError);
    video.src = videoUrl;
  });
};

// 智能预加载下一个视频
const preloadNextVideos = async () => {
  // 检查是否应该预加载
  if (isPreloading.value || !currentVideo.value) {
    return;
  }

  // 使用优化器判断是否应该预加载
  if (!videoOptimizer.shouldPreload(bufferHealth.value, isPlaying.value)) {
    console.log('跳过预加载：优化器建议不预加载');
    return;
  }

  // 如果当前视频还在加载，延迟预加载
  if (isLoading.value || isBuffering.value) {
    console.log('当前视频加载中，延迟预加载');
    setTimeout(() => preloadNextVideos(), 5000);
    return;
  }

  isPreloading.value = true;
  console.log('开始智能预加载...');

  try {
    const currentIndex = playlist.value.findIndex(v => v.id === currentVideo.value?.id);
    const config = videoOptimizer.getConfig();
    const preloadCount = config.preloadCount;

    if (preloadCount === 0) {
      console.log('预加载已禁用');
      return;
    }

    const nextVideos = playlist.value.slice(currentIndex + 1, currentIndex + 1 + preloadCount);
    console.log(`预加载${nextVideos.length}个视频`);

    for (const video of nextVideos) {
      if (video.url && !videoPreloadCache.has(video.url)) {
        try {
          // 使用优化后的URL进行预加载
          const optimizedUrl = videoOptimizer.getOptimizedVideoUrl(video.url);
          await preloadVideoMetadata(optimizedUrl);
          console.log('预加载完成:', video.title);

          // 根据网络状况调整延迟
          const delay = isSlowNetwork.value ? 3000 : 1500;
          await new Promise(resolve => setTimeout(resolve, delay));

          // 检查是否需要停止预加载（网络状况变化）
          if (!videoOptimizer.shouldPreload(bufferHealth.value, isPlaying.value)) {
            console.log('网络状况变化，停止预加载');
            break;
          }
        } catch (error) {
          console.warn('预加载视频失败:', video.url, error);
          // 预加载失败时停止后续预加载
          break;
        }
      }
    }
  } catch (error) {
    console.error('预加载过程出错:', error);
  } finally {
    isPreloading.value = false;
    console.log('预加载完成');
  }
};

// 视频事件处理
const onVideoLoadStart = () => {
  console.log('🎬 视频开始加载:', currentVideo.value?.url);
  console.log('🔍 当前视频信息:', {
    id: currentVideo.value?.id,
    title: currentVideo.value?.title,
    url: currentVideo.value?.url,
    index: currentIndex.value
  });

  // 检测网络状态
  detectNetworkSpeed();

  // 重置所有状态
  isVideoReady.value = false;
  isLoading.value = true;
  isBuffering.value = false;
  showLoadingProgress.value = true;
  showRetryButton.value = false;
  loadingProgress.value = 0;
  bufferHealth.value = 0;

  // 根据网络状态设置初始提示
  if (isSlowNetwork.value) {
    loadingText.value = `检测到慢网络 (${networkStatus.value})，正在优化加载...`;
  } else {
    loadingText.value = '正在连接视频服务器...';
  }

  // 设置加载超时
  setLoadingTimeout();

  // 重置播放状态
  isPlaying.value = false;
  currentTime.value = 0;
  duration.value = 0;
  progressValue.value = 0;

  console.log(`加载配置 - 网络: ${networkStatus.value}, 预加载: ${videoPreloadMode.value}, 慢网络: ${isSlowNetwork.value}`);
};

const onVideoLoadedMetadata = () => {
  console.log('视频元数据加载完成');
  loadingText.value = '视频信息加载完成，正在缓冲...';
  loadingProgress.value = 20;

  if (videoPlayer.value) {
    duration.value = videoPlayer.value.duration;
    console.log('视频时长:', duration.value);

    // 设置进度跟踪器的视频时长
    if (progressTracker.value) {
      progressTracker.value.setDuration(duration.value);
    }
  }
};

// 视频缓冲进度
const onVideoProgress = () => {
  if (!videoPlayer.value || !duration.value) return;

  const buffered = videoPlayer.value.buffered;
  if (buffered.length > 0) {
    const bufferedEnd = buffered.end(buffered.length - 1);
    const bufferedPercent = Math.round((bufferedEnd / duration.value) * 100);
    const currentTime = videoPlayer.value.currentTime;

    // 使用优化器计算缓冲健康度
    bufferHealth.value = videoOptimizer.calculateBufferHealth(videoPlayer.value);

    // 更新加载进度（至少显示40%，最多95%，为canplay事件留空间）
    loadingProgress.value = Math.min(Math.max(bufferedPercent, 40), 95);

    // 根据缓冲健康度调整提示文本
    if (bufferHealth.value < 20 && isPlaying.value) {
      loadingText.value = `缓冲不足，正在加载... ${Math.round(bufferedEnd)}s / ${Math.round(duration.value)}s`;
    } else {
      loadingText.value = `正在缓冲视频... ${Math.round(bufferedEnd)}s / ${Math.round(duration.value)}s`;
    }

    console.log(`视频缓冲进度: ${bufferedPercent}%, 已缓冲: ${bufferedEnd}s, 缓冲健康度: ${bufferHealth.value}%`);

    // 如果缓冲健康度低且正在播放，显示缓冲提示
    if (bufferHealth.value < 10 && isPlaying.value && !isBuffering.value) {
      isBuffering.value = true;
      showLoadingProgress.value = true;
    } else if (bufferHealth.value > 50 && isBuffering.value) {
      isBuffering.value = false;
      showLoadingProgress.value = false;
    }
  }
};

const onVideoCanPlay = () => {
  console.log('视频可以播放');
  loadingText.value = '视频准备就绪...';
  loadingProgress.value = 95;

  // 重置缓冲状态
  isBuffering.value = false;

  // 如果是慢网络，提前结束加载状态
  if (isSlowNetwork.value) {
    setTimeout(() => {
      if (isLoading.value) {
        onVideoCanPlayThrough();
      }
    }, 1000);
  }
};

const onVideoCanPlayThrough = () => {
  console.log('视频可以流畅播放');

  // 结束性能监控
  if (currentVideo.value) {
    PerformanceMonitor.endTimer(`video-switch-${currentVideo.value.id}`);
  }

  // 清除加载超时
  clearLoadingTimeout();

  // 完成加载进度
  loadingProgress.value = 100;
  loadingText.value = '加载完成！';

  // 重置重试计数
  retryCount.value = 0;
  stallCount.value = 0;

  // 延迟隐藏加载界面，让用户看到100%完成
  const hideDelay = isSlowNetwork.value ? 200 : 500; // 慢网络时更快隐藏
  setTimeout(() => {
    isVideoReady.value = true;
    isLoading.value = false;
    isBuffering.value = false;
    showLoadingProgress.value = false;

    // 创建进度跟踪器
    initProgressTracker();

    // 视频加载完成后，根据网络状况决定是否预加载
    const preloadDelay = isSlowNetwork.value ? 10000 : 2000; // 慢网络延迟更久
    setTimeout(() => {
      preloadNextVideos();
    }, preloadDelay);
  }, hideDelay);

  // 应用视频设置
  if (videoPlayer.value) {
    videoPlayer.value.muted = videoSettings.value.muted;
    videoPlayer.value.loop = videoSettings.value.loop;
    videoPlayer.value.playbackRate = videoSettings.value.playbackRate;

    // 如果设置了自动播放，尝试播放
    if (videoSettings.value.autoplay) {
      videoPlayer.value.play().catch(error => {
        console.warn('自动播放失败:', error);
        // 大多数浏览器需要用户交互后才能播放带声音的视频
        // 如果需要自动播放，可以尝试静音播放
        if (!videoSettings.value.muted && videoPlayer.value) {
          console.log('尝试静音自动播放');
          videoSettings.value.muted = true;
          videoPlayer.value.muted = true;
          videoPlayer.value.play().catch(e => {
            console.error('静音自动播放也失败:', e);
          });
        }
      });
    }
  }

  console.log('视频已准备就绪，等待用户操作');
};

const onVideoPlay = () => {
  console.log('视频开始播放');
  isPlaying.value = true;
  resetControlsTimer();

  // 通知进度跟踪器开始播放
  if (progressTracker.value) {
    progressTracker.value.onPlay();
  }
};

const onVideoPause = () => {
  console.log('视频暂停');
  isPlaying.value = false;
  showControls.value = true;
  if (controlsTimer) {
    clearTimeout(controlsTimer);
  }

  // 通知进度跟踪器暂停播放
  if (progressTracker.value) {
    progressTracker.value.onPause();
  }
};

const onVideoEnded = () => {
  console.log('视频播放结束');
  isPlaying.value = false;
  showControls.value = true;

  // 通知进度跟踪器视频结束
  if (progressTracker.value) {
    progressTracker.value.onEnded();
  }

  // 标记当前课时为已完成
  if (currentVideo.value) {
    markLessonCompleted(currentVideo.value.id);
    showToast('🎉 课时学习完成！');
  }

  // 自动播放下一个视频
  if (currentIndex.value < playlist.value.length - 1) {
    const nextVideo = playlist.value[currentIndex.value + 1];
    console.log('自动播放下一个视频:', nextVideo.title);

    // 延迟2秒后自动播放下一个视频，给用户时间看到完成提示
    setTimeout(() => {
      playVideo(nextVideo, currentIndex.value + 1);
    }, 2000);
  } else {
    console.log('🎊 恭喜！已完成所有课程学习');
    showToast('🎊 恭喜！已完成所有课程学习');
  }
};

const onVideoTimeUpdate = () => {
  if (!videoPlayer.value || isDragging.value) return;

  currentTime.value = videoPlayer.value.currentTime;

  if (duration.value > 0) {
    progressValue.value = (currentTime.value / duration.value) * 100;
  }

  // 通知进度跟踪器时间更新
  if (progressTracker.value) {
    progressTracker.value.onTimeUpdate(currentTime.value);
  }
};

const onVideoWaiting = () => {
  console.log('视频缓冲中...');
  isBuffering.value = true;
  loadingText.value = '视频缓冲中，请稍候...';

  // 如果频繁缓冲，建议降低画质
  stallCount.value++;
  if (stallCount.value > 3 && !isSlowNetwork.value) {
    console.warn('检测到频繁缓冲，可能需要降低画质');
    showToast('网络较慢，建议降低画质');
  }
};

const onVideoStalled = () => {
  console.warn('视频播放卡顿');
  isBuffering.value = true;
  stallCount.value++;

  // 卡顿时显示提示
  if (stallCount.value > 2) {
    loadingText.value = '网络不稳定，正在重新缓冲...';
    showLoadingProgress.value = true;
  }
};

const onVideoError = (event: Event) => {
  console.error('视频播放错误:', event);
  console.error('当前视频URL:', currentVideo.value?.url);

  // 清除加载超时
  clearLoadingTimeout();

  // 立即重置状态
  isVideoReady.value = false;
  isLoading.value = false;
  isBuffering.value = false;

  const target = event.target as HTMLVideoElement;
  if (target && target.error) {
    console.error('视频错误详情:', {
      code: target.error.code,
      message: target.error.message,
      MEDIA_ERR_ABORTED: target.error.MEDIA_ERR_ABORTED,
      MEDIA_ERR_NETWORK: target.error.MEDIA_ERR_NETWORK,
      MEDIA_ERR_DECODE: target.error.MEDIA_ERR_DECODE,
      MEDIA_ERR_SRC_NOT_SUPPORTED: target.error.MEDIA_ERR_SRC_NOT_SUPPORTED
    });

    // 根据错误类型显示不同的提示
    let errorMessage = '视频加载失败';
    switch (target.error.code) {
      case target.error.MEDIA_ERR_ABORTED:
        errorMessage = '视频加载被中断';
        break;
      case target.error.MEDIA_ERR_NETWORK:
        errorMessage = '网络错误，无法加载视频';
        // 网络错误时自动重试
        if (retryCount.value < maxRetries.value) {
          setTimeout(() => {
            retryVideoLoad();
          }, 2000);
          return;
        }
        break;
      case target.error.MEDIA_ERR_DECODE:
        errorMessage = '视频解码错误';
        break;
      case target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
        errorMessage = '不支持的视频格式或来源';
        break;
    }
    showToast(errorMessage);
  } else {
    showToast('视频播放失败');
  }
};

// 检查用户是否已报名课程
const checkEnrollmentStatus = async (courseId: number) => {
  if (enrollmentChecking.value) return;

  enrollmentChecking.value = true;

  try {
    console.log('🔍 检查课程报名状态...');
    const result = await StudyService.checkEnrollmentStatus(courseId);

    if (result && result.code === 200) {
      isEnrolled.value = result.data.isEnrolled;
      console.log('✅ 报名状态检查完成:', isEnrolled.value ? '已报名' : '未报名');

      if (!isEnrolled.value) {
        // 用户未报名，显示报名弹窗
        showEnrollmentModal.value = true;
        return false;
      }
      return true;
    } else {
      console.warn('⚠️ 无法获取报名状态，允许继续观看');
      isEnrolled.value = true; // 默认允许观看
      return true;
    }
  } catch (error) {
    console.error('❌ 检查报名状态失败:', error);
    // 检查失败时默认允许观看，避免影响用户体验
    isEnrolled.value = true;
    return true;
  } finally {
    enrollmentChecking.value = false;
  }
};

// 处理报名弹窗关闭
const handleEnrollmentClose = () => {
  showEnrollmentModal.value = false;
  // 用户取消报名，返回课程详情页
  router.back();
};

// 处理报名成功
const handleEnrollmentSuccess = () => {
  isEnrolled.value = true;
  showEnrollmentModal.value = false;
  showToast('报名成功，开始学习吧！');

  // 报名成功后重新初始化视频播放器
  nextTick(() => {
    if (videoPlayer.value) {
      videoPlayer.value.load();
    }
  });
};

// 检查是否可以播放指定课时（顺序播放控制）
const canPlayLesson = (targetLessonIndex: number): boolean => {
  if (!sequentialPlayback.value) {
    return true; // 如果未启用顺序播放，允许播放任何课时
  }

  // 第一个课时总是可以播放
  if (targetLessonIndex === 0) {
    return true;
  }

  // 检查前面的课时是否都已完成
  for (let i = 0; i < targetLessonIndex; i++) {
    const lesson = playlist.value[i];
    if (lesson && !completedLessons.value.has(lesson.id)) {
      return false;
    }
  }

  return true;
};

// 获取下一个需要完成的课时
const getNextRequiredLesson = (targetLessonIndex: number): any | null => {
  for (let i = 0; i < targetLessonIndex; i++) {
    const lesson = playlist.value[i];
    if (lesson && !completedLessons.value.has(lesson.id)) {
      return { lesson, index: i };
    }
  }
  return null;
};

// 处理顺序播放限制
const handleSequentialPlaybackRestriction = (targetLessonIndex: number) => {
  const nextRequired = getNextRequiredLesson(targetLessonIndex);
  if (nextRequired) {
    showToast(`请先完成第${nextRequired.index + 1}课：${nextRequired.lesson.title}`);
    showSequentialModal.value = true;

    // 3秒后自动跳转到需要完成的课时
    setTimeout(() => {
      showSequentialModal.value = false;
      playVideo(nextRequired.lesson, nextRequired.index);
    }, 3000);
  }
};

// 标记课时为已完成
const markLessonCompleted = async (lessonId: number) => {
  // 先在前端标记为完成，提供即时反馈
  completedLessons.value.add(lessonId);
  console.log(`✅ 课时 ${lessonId} 已标记为完成`);

  // 调用后端API记录完成状态
  try {
    const courseId = Number(route.query.courseId);
    if (courseId) {
      await StudyService.markLessonCompleted(courseId, lessonId);
    }
  } catch (error) {
    console.error('❌ 后端标记课时完成失败:', error);
    // 如果后端调用失败，可以选择是否回滚前端状态
    // completedLessons.value.delete(lessonId);
  }
};

// 从后端加载已完成的课时列表
const loadCompletedLessons = async (courseId: number) => {
  try {
    console.log('🔍 加载已完成课时列表...');
    const result = await StudyService.getCourseProgress(courseId);

    if (result && result.code === 200 && result.data && result.data.lessons) {
      const completed = result.data.lessons
        .filter((lesson: any) => lesson.isCompleted)
        .map((lesson: any) => lesson.id);

      completedLessons.value = new Set(completed);
      console.log('✅ 已完成课时列表加载成功:', Array.from(completedLessons.value));
    }
  } catch (error) {
    console.error('❌ 加载已完成课时列表失败:', error);
  }
};

// 初始化进度跟踪器
const initProgressTracker = async () => {
  // 防止重复初始化
  if (progressTrackerInitialized.value || progressTracker.value) {
    console.log('⚠️ 进度跟踪器已初始化，跳过重复初始化');
    return;
  }

  const courseId = Number(route.query.courseId);
  const lessonId = Number(route.params.id);

  if (!courseId || !lessonId) {
    console.warn('⚠️ 缺少课程ID或课时ID，无法初始化进度跟踪器');
    return;
  }

  try {
    progressTrackerInitialized.value = true;
    console.log('🚀 开始初始化进度跟踪器...');

    // 创建新的进度跟踪器
    progressTracker.value = new VideoProgressTracker(courseId, lessonId);

    // 设置视频时长
    if (duration.value > 0) {
      progressTracker.value.setDuration(duration.value);
    }

    // 获取断点续播位置（只获取一次）
    const resumePosition = await progressTracker.value.getResumePosition();
    if (resumePosition > 0 && videoPlayer.value) {
      console.log(`🔄 设置断点续播位置: ${resumePosition}秒`);
      videoPlayer.value.currentTime = resumePosition;
      currentTime.value = resumePosition;

      // 更新进度条
      if (duration.value > 0) {
        progressValue.value = (resumePosition / duration.value) * 100;
      }
    }

    // 开始跟踪
    progressTracker.value.startTracking();

    console.log('✅ 进度跟踪器初始化完成');
  } catch (error) {
    console.error('❌ 进度跟踪器初始化失败:', error);
    progressTrackerInitialized.value = false; // 失败时重置状态，允许重试
  }
};

// 工具函数
const formatTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

const formatDate = (dateString?: string): string => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 全屏事件监听
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement;
};

// 页面初始化
const initVideoPlayer = async () => {
  // 防止重复初始化
  if (isInitializing.value) {
    console.log('正在初始化中，跳过重复调用');
    return;
  }

  try {
    // 开始初始化性能监控
    PerformanceMonitor.startTimer('video-player-init');

    isInitializing.value = true;
    isVideoReady.value = false;
    isLoading.value = true;

    // 设置初始化超时（8秒）
    const initTimeout = setTimeout(() => {
      if (isLoading.value) {
        console.warn('初始化超时，强制重置加载状态');
        isLoading.value = false;
        isInitializing.value = false;
        showToast('视频初始化超时，请刷新页面重试');
      }
    }, 8000);

    // 获取路由参数
    const lessonId = Number(route.params.id);
    const courseId = Number(route.query.courseId);
    const title = route.query.title;

    if (title) {
      videoTitle.value = decodeURIComponent(title as string);
    }

    console.log('初始化视频播放器，课程ID:', courseId, '课时ID:', lessonId);

    if (courseId && lessonId) {
      // 清除初始化超时
      clearTimeout(initTimeout);

      // 检查缓存，避免重复API调用
      let courseResult = courseCache.value.get(courseId);
      if (!courseResult) {
        console.log('从API获取课程数据...');
        courseResult = await PerformanceMonitor.monitorApiCall(
          `course-detail-${courseId}`,
          () => StudyService.getCourseDetail(courseId)
        );
        if (courseResult) {
          courseCache.value.set(courseId, courseResult);
          console.log('✅ 课程数据已缓存');
        }
      } else {
        console.log('✅ 使用缓存的课程数据');
      }

      // 检查用户是否已报名课程
      if (courseResult && courseResult.data) {
        // 保存课程信息用于报名弹窗
        courseInfo.value = courseResult.data;

        const enrollmentAllowed = await checkEnrollmentStatus(courseId);
        if (!enrollmentAllowed) {
          // 用户未报名，停止初始化
          isInitializing.value = false;
          isLoading.value = false;
          console.log('⚠️ 用户未报名课程，停止视频初始化');
          return;
        }

        // 加载已完成的课时列表
        await loadCompletedLessons(courseId);
      }

      if (courseResult && courseResult.data) {
        const courseData = courseResult.data;
        console.log('✅ 课程详情加载成功:', courseData.title);

        // 从章节中提取所有课时，构建播放列表
        const allLessons: any[] = [];
        if (courseData.chapters && Array.isArray(courseData.chapters)) {
          courseData.chapters.forEach((chapter: any) => {
            if (chapter.lessons && Array.isArray(chapter.lessons)) {
              chapter.lessons.forEach((lesson: any) => {
                if (lesson.video_url) { // 只添加有视频URL的课时
                  // 使用优化器获取优化后的视频URL
                  const originalUrl = lesson.video_url;
                  const optimizedUrl = videoOptimizer.getOptimizedVideoUrl(originalUrl);
                  console.log('原始URL:', originalUrl);
                  console.log('优化后URL:', optimizedUrl);

                  allLessons.push({
                    id: lesson.id,
                    title: lesson.title,
                    url: optimizedUrl,
                    originalUrl: originalUrl, // 保存原始URL用于重试
                    poster: lesson.poster || '',
                    duration: lesson.duration,
                    description: lesson.description,
                    chapterTitle: chapter.title,
                    viewCount: lesson.view_count || 0,
                    isCompleted: false, // 可以根据学习进度API来设置
                    createdAt: lesson.created_at
                  });
                }
              });
            }
          });
        }

        playlist.value = allLessons;
        console.log('✅ 播放列表构建完成，共', allLessons.length, '个视频');

        // 找到当前要播放的课时
        const currentLesson = allLessons.find(lesson => lesson.id === lessonId);
        if (currentLesson) {
          const index = allLessons.findIndex(lesson => lesson.id === lessonId);
          const finalIndex = index === -1 ? 0 : index;

          console.log('✅ 找到当前播放视频:', currentLesson.title);

          // 使用 nextTick 确保 DOM 更新后再设置视频
          nextTick(() => {
            currentVideo.value = currentLesson;
            videoTitle.value = currentLesson.title;
            currentIndex.value = finalIndex;
            console.log('✅ 视频数据设置完成，等待视频加载事件');

            // 设置一个备用超时，如果视频元素没有触发loadstart事件
            setTimeout(() => {
              if (isLoading.value && !isVideoReady.value) {
                console.warn('视频可能无法加载，重置加载状态');
                isLoading.value = false;
              }
            }, 3000);
          });
        } else {
          console.log('⚠️ 未找到指定的课时ID:', lessonId);
          // 如果没找到指定课时，播放第一个视频
          if (allLessons.length > 0) {
            console.log('✅ 使用第一个课时:', allLessons[0].title);

            nextTick(() => {
              currentVideo.value = allLessons[0];
              videoTitle.value = allLessons[0].title;
              currentIndex.value = 0;
              console.log('✅ 默认视频数据设置完成，等待视频加载事件');

              // 设置一个备用超时，如果视频元素没有触发loadstart事件
              setTimeout(() => {
                if (isLoading.value && !isVideoReady.value) {
                  console.warn('默认视频可能无法加载，重置加载状态');
                  isLoading.value = false;
                }
              }, 3000);
            });
          } else {
            currentVideo.value = null;
            isLoading.value = false; // 重要：没有视频时重置加载状态
            console.log('⚠️ 课程中没有可播放的视频');
          }
        }
      } else {
        console.log('⚠️ 课程详情数据为空');
        playlist.value = [];
        currentVideo.value = null;
        isLoading.value = false; // 重要：没有数据时重置加载状态
      }
    } else {
      console.log('⚠️ 缺少必要的路由参数 - courseId:', courseId, 'lessonId:', lessonId);
      playlist.value = [];
      currentVideo.value = null;
      isLoading.value = false; // 重要：参数错误时重置加载状态
    }
  } catch (error) {
    console.error('初始化视频播放器失败:', error);
    // 错误时清空数据
    playlist.value = [];
    currentVideo.value = null;
    isLoading.value = false; // 错误时重置加载状态
  } finally {
    isInitializing.value = false; // 重置初始化状态
    PerformanceMonitor.endTimer('video-player-init');
  }
};

// 移除可能导致重复加载的 watch 监听器
// 现在通过直接设置 src 属性来更新视频，Vue 的响应式系统会自动处理

// 生命周期
onMounted(() => {
  // 启动网络监控
  videoOptimizer.startNetworkMonitoring();

  // 初始化视频设置
  // 可以从本地存储中读取用户之前的设置
  const savedSettings = localStorage.getItem('videoSettings');
  if (savedSettings) {
    try {
      const parsedSettings = JSON.parse(savedSettings);
      videoSettings.value = { ...videoSettings.value, ...parsedSettings };
      console.log('已加载保存的视频设置:', videoSettings.value);
    } catch (e) {
      console.error('解析保存的视频设置失败:', e);
    }
  }

  // 更新操作选项文本
  updateMoreActions();

  // 初始化视频播放器
  initVideoPlayer();

  // 监听全屏变化
  document.addEventListener('fullscreenchange', handleFullscreenChange);

  // 阻止页面滚动（全屏时）
  document.body.style.overflow = 'hidden';
});

onUnmounted(() => {
  // 清理进度跟踪器
  if (progressTracker.value) {
    progressTracker.value.stopTracking();
    progressTracker.value.destroy();
    progressTracker.value = null;
    console.log('🗑️ 进度跟踪器已清理');
  }
  // 重置初始化状态
  progressTrackerInitialized.value = false;

  // 清理定时器
  if (controlsTimer) {
    clearTimeout(controlsTimer);
  }

  // 清理加载超时
  clearLoadingTimeout();

  // 移除事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange);

  // 恢复页面滚动
  document.body.style.overflow = '';
});
</script>

<style lang="scss" scoped>
.video-player-page {
  min-height: 100vh;
  background-color: #000;
  display: flex;
  flex-direction: column;
}

// 视频容器
.video-container {
  position: relative;
  width: 100%;
  height: 56.25vw; // 16:9 比例
  max-height: 50vh;
  background: #000;
  overflow: hidden;
}

.video-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.video-element {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;

  &::-webkit-media-controls {
    display: none !important;
  }

  &::-webkit-media-controls-enclosure {
    display: none !important;
  }
}

.empty-state {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
}

.empty-content {
  text-align: center;
  color: #fff;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-text {
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
  color: #fff;
}

.empty-desc {
  font-size: 0.9rem;
  color: #999;
}

// 自定义控制层
.video-controls {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.3) 0%,
    transparent 30%,
    transparent 70%,
    rgba(0, 0, 0, 0.5) 100%
  );
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.controls-overlay {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 4.26667vw;
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 16vw;
  height: 16vw;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    transform: translate(-50%, -50%) scale(0.95);
  }
}

.progress-container {
  margin-top: auto;
  padding: 2.13333vw 0;
}

.time-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2.13333vw;
  font-size: 3.46667vw;
  color: #fff;
}

.control-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 3.2vw;
  margin-bottom: 2.13333vw;
}

.control-button {
  width: 8vw;
  height: 8vw;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:active {
    transform: scale(0.95);
  }
}

.speed-text {
  color: #fff;
  font-size: 3.2vw;
  font-weight: 500;
}

// 加载状态
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 20;

  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 6.66667vw;

    .loading-info {
      margin-top: 4vw;

      .loading-text {
        color: #fff;
        font-size: 3.73333vw;
        margin-bottom: 2.66667vw;
      }

      .loading-progress {
        margin-bottom: 4vw;

        .progress-bar {
          width: 53.33333vw;
          height: 1.06667vw;
          background: rgba(255, 255, 255, 0.3);
          border-radius: 0.53333vw;
          overflow: hidden;
          margin-bottom: 1.33333vw;

          .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #1989fa, #4fc3f7);
            border-radius: 0.53333vw;
            transition: width 0.3s ease;
          }
        }

        .progress-text {
          color: #fff;
          font-size: 3.2vw;
          opacity: 0.8;
        }
      }

      .loading-tips {
        .tip-item {
          color: rgba(255, 255, 255, 0.7);
          font-size: 3.2vw;
          margin-bottom: 1.33333vw;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }

      .retry-section {
        margin-top: 4vw;

        .van-button {
          background: #1989fa;
          border-color: #1989fa;
          font-size: 3.46667vw;
          padding: 2.13333vw 4.26667vw;
        }
      }
    }
  }
}

// 淡入淡出过渡效果
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 视频信息
.video-info {
  background: #fff;
  padding: 4.26667vw;
  border-bottom: 1px solid #ebedf0;
}

.video-title {
  font-size: 4.8vw;
  font-weight: 600;
  color: #323233;
  margin: 0 0 2.13333vw 0;
  line-height: 1.4;
}

.video-description {
  font-size: 3.73333vw;
  color: #646566;
  line-height: 1.5;
  margin: 0 0 3.2vw 0;
}

.video-meta {
  display: flex;
  gap: 4.26667vw;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 1.06667vw;
  font-size: 3.46667vw;
  color: #969799;
}

// 播放列表
.playlist-section {
  flex: 1;
  background: #f7f8fa;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.playlist-header {
  background: #fff;
  padding: 4.26667vw;
  border-bottom: 1px solid #ebedf0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    font-size: 4.26667vw;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .playlist-count {
    font-size: 3.46667vw;
    color: #969799;
  }
}

.playlist-content {
  flex: 1;
  overflow-y: auto;
  padding: 2.13333vw 0;
}

.playlist-item {
  display: flex;
  align-items: center;
  gap: 3.2vw;
  padding: 3.2vw 4.26667vw;
  background: #fff;
  margin-bottom: 2.13333vw;
  cursor: pointer;
  transition: all 0.3s ease;

  &.active {
    background: #f0f8ff;
    border-left: 4px solid #1989fa;
  }

  &.loading {
    background: #f7f8fa;
    opacity: 0.8;

    &::after {
      content: '';
      position: absolute;
      right: 4.26667vw;
      width: 4vw;
      height: 4vw;
      border: 2px solid #1989fa;
      border-top: 2px solid transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
  }

  &:active {
    background: #ebedf0;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.item-index {
  width: 6.4vw;
  height: 6.4vw;
  border-radius: 50%;
  background: #f7f8fa;
  color: #646566;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3.2vw;
  font-weight: 600;
  flex-shrink: 0;

  .active & {
    background: #1989fa;
    color: #fff;
  }
}

.item-thumbnail {
  position: relative;
  width: 21.33333vw;
  height: 12vw;
  border-radius: 1.6vw;
  overflow: hidden;
  flex-shrink: 0;

  .thumbnail-image {
    width: 100%;
    height: 100%;
  }

  .play-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 6.4vw;
    height: 6.4vw;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-title {
  font-size: 3.73333vw;
  font-weight: 500;
  color: #323233;
  margin: 0 0 1.6vw 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;

  .active & {
    color: #1989fa;
  }
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 2.13333vw;
}

.item-duration {
  font-size: 3.2vw;
  color: #969799;
}

// 全屏样式
:global(.video-player-page) {
  &:fullscreen {
    .video-container {
      height: 100vh;
      max-height: none;
    }

    .video-info,
    .playlist-section {
      display: none;
    }
  }
}

// 响应式设计
@media (min-width: 768px) {
  .video-player-page {
    max-width: 768px;
    margin: 0 auto;
  }

  .video-container {
    height: 432px; // 768 * 9/16
  }
}

// 横屏适配
@media (orientation: landscape) and (max-height: 500px) {
  .video-container {
    height: 100vh;
    max-height: none;
  }

  .video-info,
  .playlist-section {
    display: none;
  }
}

// 空状态样式
.empty-state {
  padding: 8vw 4vw;
  background-color: #000;
  color: #fff;

  .van-empty__description {
    color: #969799;
    font-size: 3.5vw;
    margin-top: 3vw;
  }

  .bottom-button {
    margin-top: 4vw;
    padding: 0 6vw;
    height: 9vw;
    font-size: 3.5vw;
  }
}

// 加载状态样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12vw 0;
  background-color: #000;

  .van-loading {
    font-size: 3.5vw;
    color: #fff;
  }
}

// 顺序播放相关样式
.playlist-item.completed {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-left: 4px solid #07c160;
}

.playlist-item.locked {
  background: #f5f5f5;
  border-left: 4px solid #d9d9d9;
  opacity: 0.6;
  cursor: not-allowed;
}

.playlist-item.locked:hover {
  background: #f5f5f5;
  transform: none;
}

.completed-icon {
  color: #07c160;
  font-weight: bold;
  font-size: 4.26667vw;
}

.locked-icon {
  color: #999;
  font-size: 3.73333vw;
}

.locked-thumbnail {
  filter: grayscale(50%);
}

.lock-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  padding: 1.06667vw;
}

.locked-title {
  color: #999;
}
</style>
